import uuid

import requests
from time import sleep

POST_URL = 'https://openspeech.bytedance.com/api/v1/tts_async_with_emotion/submit'
QUERY_URL = 'https://openspeech.bytedance.com/api/v1/tts_async_with_emotion/query'
ACCESS_TOKEN = '19IhMhOpEcMB3rejNUNKLNyncnaRGcAz'

# https://www.volcengine.com/docs/6561/97465#%E5%A4%9A%E6%83%85%E6%84%9F-%E9%A3%8E%E6%A0%BC-%E8%AF%AD%E8%A8%80%E9%85%8D%E7%BD%AE%E4%BF%A1%E6%81%AF
VOICE_TYPES = {
    '擎苍': 'BV701_streaming',
    '阳光青年': 'BV123_streaming',
    '反卷青年': 'BV120_streaming',
    '通用赘婿': 'BV119_streaming',
    '古风少御': 'BV115_streaming',
    '霸气青叔': 'BV107_streaming',
    '质朴青年': 'BV100_streaming',
    '温柔淑女': 'BV104_streaming',
    '开朗青年': 'BV004_streaming',
    '甜宠少御': 'BV113_streaming',
    '儒雅青年': 'BV102_streaming'
}


def create_header():
    return {
        'Resource-Id': 'volc.tts_async.emotion',
        'Authorization': 'Bearer; ' + ACCESS_TOKEN
    }


def post_voice_synthesis(text, voice_type):
    data = {
        'appid': '8365454948',
        'reqid': str(uuid.uuid4()),
        'text': text,
        'format': 'mp3',
        'voice_type': voice_type
    }
    response = requests.post(POST_URL, json=data, headers=create_header())
    data = response.json()
    print(data)
    return data


def query_result(p_task_id):
    data = {
        'appid': '8365454948',
        'task_id': p_task_id,
    }
    response = requests.get(QUERY_URL, params=data, headers=create_header())
    data = response.json()
    print(data)
    if response.status_code == 200:
        return data
    else:
        return None


# task = post_voice_synthesis('你好', VOICE_TYPES.get('反卷青年'))
# task_id = task['task_id']
# times = 0
# success = False
# while not success:
#     sleep(2)
#     times += 1
#     result = query_result(task_id)
#     if result is None:
#         continue
#     else:
#         success = True
#         print(result['audio_url'])
#     print(times)
